package com.demo.controller;

import com.demo.common.ResultData;
import com.demo.request.EmailSenderReq;
import com.demo.sender.email.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 邮件
 *
 * @author wangfengchen
 */
@Slf4j
@RestController
@RequestMapping("/email")
public class EmailController {

  @Autowired
  private AwsEmailSender awsEmailSender;
  @Autowired
  private MailGunEmailBasicSender mailGunEmailSender;
  @Autowired
  private EmailSenderService emailSenderService;
  @Autowired
  private AttachmentValidator attachmentValidator;


  /**
   * 检查aws是否有剩余发送配额
   *
   * @return
   */
  @GetMapping("/checkAwsQuota")
  public ResultData<Boolean> sendAws() {
    return ResultData.success(awsEmailSender.checkSendQuota());
  }


  /**
   * 测试同步发送AWS邮件
   *
   * @param request
   * @return
   */
  @PostMapping("/sendAws")
  public ResultData<Object> sendAws(@RequestBody EmailSenderReq request) {
    // Example usage: 特别注意aws必须开放白名单，否则403
    try {
      String bodyText = "您的验证码为：%s，5分钟内有效，如不是本人操作，请联系安全部。";
      bodyText = String.format(bodyText, request.getAuthCode());
      request.setBodyText(bodyText);
      return awsEmailSender.send(request);
    } catch (Exception e) {
      log.error("e = {}", ExceptionUtils.getStackTrace(e));
      return ResultData.fail();
    }
  }

  /**
   * 测试异步发送AWS邮件
   *
   * @param request
   * @return
   */
  @PostMapping("/sendAwsAsync")
  public ResultData<Object> sendAwsAsync(@RequestBody EmailSenderReq request) {
    // Example usage: 特别注意aws必须开放白名单，否则403
    try {
      String bodyText = "您的验证码为：%s，5分钟内有效，如不是本人操作，请联系安全部。";
      bodyText = String.format(bodyText, request.getAuthCode());
      request.setBodyText(bodyText);
      return awsEmailSender.sendAsync(request);
    } catch (Exception e) {
      log.error("e = {}", ExceptionUtils.getStackTrace(e));
      return ResultData.fail();
    }
  }

  /**
   * 测试同步发送MailGun邮件
   *
   * @return
   */
  @GetMapping("/sendMailGun")
  public ResultData<Object> sendMailGun(@RequestParam String authCode, @RequestParam String toAddress) {
    try {
      String subject = "请查收您的验证码";
      String bodyHtml = "您的验证码为：%s，5分钟内有效，如不是本人操作，请联系安全部。";
      bodyHtml = String.format(bodyHtml, authCode);
      String bodyText = "";
      return mailGunEmailSender.send(toAddress, subject, bodyHtml, bodyText);
    } catch (Exception e) {
      log.error("e = {}", ExceptionUtils.getStackTrace(e));
      return ResultData.fail();
    }
  }

  /**
   * 测试异步发送MailGun邮件
   *
   * @return
   */
  @GetMapping("/sendMailGunAsync")
  public ResultData<Object> sendMailGunAsync(@RequestParam String authCode, @RequestParam String toAddress) {
    try {
      String subject = "请查收您的验证码";
      String bodyHtml = "您的验证码为：%s，5分钟内有效，如不是本人操作，请联系安全部。";
      bodyHtml = String.format(bodyHtml, authCode);
      String bodyText = "";
      return mailGunEmailSender.sendAsync(toAddress, subject, bodyHtml, bodyText);
    } catch (Exception e) {
      log.error("e = {}", ExceptionUtils.getStackTrace(e));
      return ResultData.fail();
    }
  }

  /**
   * 测试同步多渠道发送邮件
   *
   * @param request
   * @return
   */
  @PostMapping("/sendChannel")
  public ResultData<Object> sendChannel(@RequestBody EmailSenderReq request) {
    try {
      String bodyText = "您的验证码为：%s，5分钟内有效，如不是本人操作，请联系安全部。";
      bodyText = String.format(bodyText, request.getAuthCode());
      request.setBodyText(bodyText);
      return emailSenderService.send(request);
    } catch (Exception e) {
      log.error("e = {}", ExceptionUtils.getStackTrace(e));
      return ResultData.fail();
    }
  }

  /**
   * 测试异步多渠道发送邮件
   *
   * @param request
   * @return
   */
  @PostMapping("/sendChannelAsync")
  public ResultData<Object> sendChannelAsync(@RequestBody EmailSenderReq request) {
    try {
      String bodyText = "您的验证码为：%s，5分钟内有效，如不是本人操作，请联系安全部。";
      bodyText = String.format(bodyText, request.getAuthCode());
      request.setBodyText(bodyText);
      return emailSenderService.sendAsync(request);
    } catch (Exception e) {
      log.error("e = {}", ExceptionUtils.getStackTrace(e));
      return ResultData.fail();
    }
  }

  /**
   * 异步发送附件
   *
   * @param request
   * @param files
   * @return
   */
  @PostMapping(value = "/sendWithAttachmentAsync")
  public ResultData<Object> sendWithAttachmentAsync(@RequestPart EmailSenderReq request, @RequestPart("files") List<MultipartFile> files) {
    List<EmailAttachment> attachmentList = files.stream().map(this::toEmailAttachment).collect(Collectors.toList());
    request.setAttachmentList(attachmentList);
    emailSenderService.sendWithAttachmentAsync(request);
    return ResultData.success();
  }

  private EmailAttachment toEmailAttachment(MultipartFile file) {
    try {
      attachmentValidator.validateFile(file);
      return new EmailAttachment(
          file.getOriginalFilename(),
          file.getBytes(),
          file.getContentType()
      );
    } catch (IOException e) {
      throw new RuntimeException("文件处理失败: " + file.getOriginalFilename(), e);
    }
  }


}
